package com.cinsea.crm.ext;

import com.alibaba.fastjson.JSON;
import com.cinsea.common.Env;
import com.cinsea.common.ExtAction;
import com.cinsea.common.JdbcDao;
import com.cinsea.common.Page;
import com.cinsea.hrm.model.Human;
import com.cinsea.hrm.service.HumanService;
import com.cinsea.htmlselect.model.Option;
import com.cinsea.htmlselect.service.OptionService;
import com.cinsea.interfaces.form.FormdataServiceImpl;
import com.cinsea.interfaces.model.Cell;
import com.cinsea.interfaces.model.Dataset;
import com.cinsea.security.util.JdbcUtil;
import com.cinsea.util.DateUtil;
import com.cinsea.util.NumberUtil;
import com.cinsea.util.StringUtil;
import com.cinsea.security.service.RightService;
import com.cinsea.interfaces.form.Formdata;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.*;

public class CrmAction extends ExtAction {
    JdbcDao jdbcDao = Env.getBean("jdbcDao");
    public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        HumanService humanService = Env.getBean("humanService");
        OptionService optionService = Env.getBean("optionService");
        String action = StringUtil.null2String(request.getParameter("action"));
        if (action.equals("getcontactlogs")) {
            int pageNo = NumberUtil.string2Int(request.getParameter("pageno"), 1);
            int pageSize = NumberUtil.string2Int(request.getParameter("pagesize"), 20);
            if (!StringUtil.isEmpty(request.getParameter("start")))
                pageNo = NumberUtil.string2Int(request.getParameter("start"), 0) / pageSize + 1;
            String crmid = StringUtil.null2String(request.getParameter("crmid"));
            String sql = "select processid,content,lxdate,lxer,sjid,attfile from ut_contactlist where deleted=0 and (crmid=? or sjid in(select id from ut_opportunities where crmid=?)) order by createdatetime desc";
            String sjid = StringUtil.null2String(request.getParameter("sjid"));
            if(!StringUtil.isEmpty(sjid))
                sql = "select processid,content,lxdate,lxer,sjid,attfile from ut_contactlist where deleted=0 and sjid=?  order by createdatetime desc";
            sql=JdbcUtil.getPermissionSql(sql,"ut_contactlist");
            Page pageObject;
            if(!StringUtil.isEmpty(sjid))
                pageObject = jdbcDao.pagedQuery(sql, new String[]{sjid}, pageNo, pageSize);
            else
                pageObject = jdbcDao.pagedQuery(sql, new String[]{crmid,crmid}, pageNo, pageSize);
            List list = new ArrayList();
            if (pageObject.getTotalSize() != 0) {
                list = (List) pageObject.getResult();
            }
            List arrayjson = new ArrayList();
            for (Object row : list) {
                Map object = new HashMap();
                String processid = (String) ((Map) row).get("processid");
                object.put("processid", processid);
                String lxer = (String) ((Map) row).get("lxer");

                if (!StringUtil.isEmpty(lxer)) {
                    String name = humanService.get(lxer).getObjname();
                    object.put("lxer", name);
                }
                String lxdate = (String) ((Map) row).get("lxdate");
                object.put("lxdate", lxdate);
                String attfile = (String) ((Map) row).get("attfile");
                if(!StringUtil.isEmpty(attfile)) object.put("attfile", "<img src='/images/base/attach.gif' />");
                String content = (String) ((Map) row).get("content");
                if(content.length()>150) content=content.substring(0,150)+"... ...<br><a href=javascript:onUrl(\"/form/formprocess.jsp?processid="+processid+"&from=report\",\"跟进记录"+lxdate+"\",\"tab"+processid+"\")>查看余下内容";
                object.put("content", content.replace("\r\n","<br>"));

                sjid = (String) ((Map) row).get("sjid");
                if (!StringUtil.isEmpty(sjid)) {
                    try {
                        sjid = (String) jdbcDao.getJdbcTemplate().queryForObject("SELECT name FROM ut_opportunities WHERE id=?", new String[]{sjid}, String.class);
                        object.put("sjid", sjid);
                    } catch (Exception e) {
                        e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                    }
                }
                arrayjson.add(object);
            }//end for
            Map jsonresult = new HashMap();
            jsonresult.put("totalcount", pageObject.getTotalSize());
            jsonresult.put("result", arrayjson);
            response.getWriter().print(JSON.toJSONString(jsonresult));
            return;
        }

        /**
         * 判断----新建客户自定义类型的个数，是否>5
         */
        if(action.equals("defineType")){
            String resultStr="";
            String currentUser = Env.getRemoteUser().getId();
            String sql = "select count(*) as types from ut_zidingyitype where cjr=?";
            Map types = jdbcDao.queryForMap(sql,new Object[]{currentUser});
            if(types!=null){
                int typeCount  = Integer.parseInt(StringUtil.null2String(types.get("types")));
                if(typeCount<5){
                    resultStr="success";
                }else{
                    resultStr="";
                }
            }
            response.getWriter().print(resultStr);
        }

        /**
         * 合并客户信息
         */
        if(action.equals("mergeCrm")){
            String mergeInfo = request.getParameter("param");
            String crm1 = request.getParameter("crm1");
            String crm2 = request.getParameter("crm2");
            List<Map> datas=(List<Map>)JSON.parse(mergeInfo);
            //1.执行更新主记录中的信息
            String mainCrm = "";
            StringBuffer updateSql = new StringBuffer("update ut_customerinfo set ");
            List paramList = new ArrayList();
            for(int i=0; i<datas.size(); i++){
                Map data = datas.get(i);
                if(StringUtil.null2String(data.get("name")).equals("mainCrm")){
                    mainCrm = StringUtil.null2String(data.get("value"));
                }else{
                    updateSql.append(data.get("name")+"=?,");
                    paramList.add(data.get("value"));
                }
            }
            String sql = updateSql.toString();
            if(sql.endsWith(",")){
                sql = sql.substring(0,sql.length()-1);
            }
            sql = sql + " where processid=?";
            paramList.add(mainCrm);
            int result = jdbcDao.update(sql,paramList.toArray());
            //2.将联系人、商机联系、商机信息三张表中的crmid更新为mainCrm，然后删除（将该记录的delete字段设为0）另外一张客户卡片；
            String[] tableName = {"ut_contactlist","ut_opportunities","ut_contact"};
            String processid = "";
            if(crm1.equals(mainCrm)){
                processid = crm2;
            }
            if(crm2.equals(mainCrm)){
                processid = crm1;
            }
            for(int k=0; k<tableName.length; k++){
                sql = "update "+tableName[k]+" set crmid=? where crmid=?";
                jdbcDao.update(sql , new Object[]{mainCrm,processid});
            }
            //删除
            sql="update cs_formprocess set deleted=1 where id=?";
            jdbcDao.update(sql,new Object[]{processid});
            sql = "update ut_customerinfo set deleted=1 where processid=?";
            jdbcDao.update(sql,new Object[]{processid});
            response.getWriter().print(result);
        }

        if(action.equals("autoComplete")){
            String queryObj = StringUtil.null2String(request.getParameter("q"));
            String sql = "select name from ut_customerinfo where deleted=0 and name like '%"+queryObj+"%'";
            sql=JdbcUtil.getPermissionSql(sql,"ut_customerinfo");
            List<Map> customerList = jdbcDao.queryForList(sql);
            String result="";
            if(customerList.size()>0){
                for(Map map : customerList){
                    result += map.get("name")+"\n";
                }
            }
            response.getWriter().print(result);
        }

        /**
         *批量修改客户经理
         */
        if(action.equals("batchUpdateManager")){
            FormdataServiceImpl formdataService = new FormdataServiceImpl();
            Formdata formData = new Formdata();
            formData.setTypeid("402881e43cfa96bb013cfb3b388b00ae");//目录id
            String currentUser = StringUtil.null2String(Env.getRemoteUser());
            formData.setOperator(currentUser);//当前用户
            Dataset dataset = new Dataset();
            String crmtype = "402881e43d269a12013d3931a0900075";//需联系客户
            String ids = StringUtil.null2String(request.getParameter("ids"));//需要修改客户经理的
            String humanid = StringUtil.null2String(request.getParameter("humanid"));//客户经理ID
            String[] array_ids = StringUtil.string2Array(ids, ",");
            //更新
            for(String id : array_ids) {
                List<Cell> mainList = new ArrayList<Cell>();
                formData.setId(id);//processid
                Cell cell1 = new Cell();
                cell1.setId("ut_customerinfo_managerid");
                cell1.setValue(humanid);
                Cell cell2 = new Cell();
                cell2.setId("ut_customerinfo_crmtype");
                cell2.setValue(crmtype);
                mainList.add(cell1);
                mainList.add(cell2);
                dataset.setMaintable(mainList);
                formData.setData(dataset);
                formdataService.modifyFormdata(formData);
            }
            //权限重构
//            RightService rightService = Env.getBean("rightService");
//            for (String processid : array_ids) {
//                rightService.reCreateRightdetail(processid, "0", "ut_customerinfo");
//            }
            response.getWriter().print("success");
        }


        if(action.equals("noContact")){
            int  day = Integer.parseInt("-"+StringUtil.null2String(request.getParameter("day")));//天数
            int pageNo = NumberUtil.string2Int(request.getParameter("pageNo"), 1);
            int pageSize = NumberUtil.string2Int(request.getParameter("pageSize"), 20);
            if (!StringUtil.isEmpty(request.getParameter("start"))){
                pageNo = NumberUtil.string2Int(request.getParameter("start"), 0) / pageSize + 1;
            }
            String date = DateUtil.dayMove(DateUtil.getCurrentDate(),day);
            List<Map> pageList = new ArrayList<Map>();
            String sql = "select processid from ut_customerinfo where processid not in (" +
                    "select crmid from ut_contactlist where lxdate>'"+date+"')";
            sql = JdbcUtil.getPermissionSql(sql,"ut_customerinfo");
            List<Map> processidList = jdbcDao.queryForList(sql);
            if(processidList.size()>0){
                int begin=0,end=20;
                if(pageNo==1){
                    pageList = getPageList(processidList,begin,end);
                }
                if(pageNo>1){
                    begin = (pageNo-1)*20;
                    end = pageNo*20;
                    pageList = getPageList(processidList,begin,end);
                }
            }
            for(Map map : pageList){
                Object[] keys = map.keySet().toArray();
                for(int a=0; a<keys.length; a++){
                    if(keys[a].equals("crmtype")){
                        Option option= optionService.get(StringUtil.null2String(map.get("crmtype")));
                        String value = option.getObjname();
                        map.put("crmtype",value);
                    }
                    if(keys[a].equals("managerid")){
                        Human human = humanService.get(StringUtil.null2String(map.get("managerid")));
                        String value = human.getObjname();
                        map.put("managerid",value);
                    }
                    if(keys[a].equals("sjjd")){
                        Option option = optionService.get(StringUtil.null2String(map.get("sjjd")));
                        String value = option.getObjname();
                        map.put("sjjd",value);
                    }
                }
            }
            Map jsonobject=new HashMap();
            jsonobject.put("totalCount",processidList.size());
            jsonobject.put("result",pageList);
            JSON jsons = (JSON)JSON.toJSON(jsonobject);
//            System.out.println("****************"+jsons);
            response.getWriter().print(JSON.toJSON(jsons));
        }
    }

    /**
     * 为   if(action.equals("noContact"))  服务
     * @param processidList
     * @param begin
     * @param end
     * @return List pageList
     */
    private List<Map> getPageList(List<Map> processidList,int begin ,int end){
        List<Map> pageList = new ArrayList<Map>();
        String sql="";
        //判断最后一次查询中剩余的数据的数目，是否大于end；否，则end=最大数目值;避免 溢出
        if(processidList.size()<end){
            end = processidList.size();
        }
        for(int index=begin; index<end; index++){
            Map info = new HashMap();
            Map map = processidList.get(index);
            sql="select name,crmtype,managerid from ut_customerinfo where processid=?";
            info = jdbcDao.queryForMap(sql, new Object[]{StringUtil.null2String(map.get("processid"))});
            map.putAll(info);
            sql = "select sjjd from ut_opportunities where crmid=? order by modifydatetime desc";
            List oppList = jdbcDao.queryForList(sql,new Object[]{StringUtil.null2String(map.get("processid"))});
            if(oppList.size()>0){
                info = (Map)oppList.get(0);
            }
            map.putAll(info);
            sql = "select lxdate,xclxrq,content from ut_contactlist where crmid=? order by lxdate desc";
            List conList = jdbcDao.queryForList(sql,new Object[]{StringUtil.null2String(map.get("processid"))});
            if(conList.size()>0){
                info = (Map)conList.get(0);
            }
            map.putAll(info);
            pageList.add(map);
        }
        return pageList;
    }
}
